﻿using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;

namespace Admin.NET.Application;

/// <summary>
/// 从机通讯服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class DeviceRelSlaveService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<DeviceRelSlave> _deviceRelSlaveRep;

    public DeviceRelSlaveService(SqlSugarRepository<DeviceRelSlave> deviceRelSlaveRep)
    {
        _deviceRelSlaveRep = deviceRelSlaveRep;
    }

    /// <summary>
    /// 分页查询从机通讯
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询从机通讯")]
    public async Task<SqlSugarPagedList<DeviceRelSlaveOutput>> Page(PageDeviceRelSlaveInput input)
    {
        input.SearchKey = input.SearchKey?.Trim();
        var query = _deviceRelSlaveRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.SlaveIp.Contains(input.SearchKey)
            )
            .WhereIF(input.DeviceSlaveTemplateId > 0, u => u.DeviceSlaveTemplateId == input.DeviceSlaveTemplateId)
            .WhereIF(input.DeviceInfoId > 0, u => u.DeviceInfoId == input.DeviceInfoId)
            .WhereIF(input.ComIdx > 0, u => u.ComIdx == input.ComIdx)
            .WhereIF(input.SlaveAddr > 0, u => u.SlaveAddr == input.SlaveAddr)
            .WhereIF(!string.IsNullOrWhiteSpace(input.SlaveIp), u => u.SlaveIp.Contains(input.SlaveIp.Trim()))
            .WhereIF(input.SlavePort > 0, u => u.SlavePort == input.SlavePort)
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<DeviceSlaveTemplate>((u, deviceslavetemplateid) => u.DeviceSlaveTemplateId == deviceslavetemplateid.Id)
            .LeftJoin<DeviceInfo>((u, deviceslavetemplateid, deviceinfoid) => u.DeviceInfoId == deviceinfoid.Id)
            .Select((u, deviceslavetemplateid, deviceinfoid) => new DeviceRelSlaveOutput
            {
                Id = u.Id,
                DeviceSlaveTemplateId = u.DeviceSlaveTemplateId,
                DeviceSlaveTemplateIdSlaveName = deviceslavetemplateid.SlaveName,
                DeviceInfoId = u.DeviceInfoId,
                DeviceInfoIdDeviceName = deviceinfoid.DeviceName,
                ComIdx = u.ComIdx,
                SlaveAddr = u.SlaveAddr,
                SlaveIp = u.SlaveIp,
                SlavePort = u.SlavePort,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加从机通讯
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加从机通讯")]
    public async Task<long> Add(AddDeviceRelSlaveInput input)
    {
        var entity = input.Adapt<DeviceRelSlave>();
        await _deviceRelSlaveRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除从机通讯
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除从机通讯")]
    public async Task Delete(DeleteDeviceRelSlaveInput input)
    {
        var entity = await _deviceRelSlaveRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _deviceRelSlaveRep.FakeDeleteAsync(entity);   //假删除
        //await _deviceRelSlaveRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新从机通讯
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新从机通讯")]
    public async Task Update(UpdateDeviceRelSlaveInput input)
    {
        var entity = input.Adapt<DeviceRelSlave>();
        await _deviceRelSlaveRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取从机通讯
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取从机通讯")]
    public async Task<DeviceRelSlave> Detail([FromQuery] QueryByIdDeviceRelSlaveInput input)
    {
        return await _deviceRelSlaveRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取从机通讯列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取从机通讯列表")]
    public async Task<List<DeviceRelSlaveOutput>> List([FromQuery] PageDeviceRelSlaveInput input)
    {
        return await _deviceRelSlaveRep.AsQueryable().Select<DeviceRelSlaveOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取从机模板Id列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeviceSlaveTemplateDeviceSlaveTemplateIdDropdown"), HttpGet]
    [DisplayName("获取从机模板Id列表")]
    public async Task<dynamic> DeviceSlaveTemplateDeviceSlaveTemplateIdDropdown()
    {
        return await _deviceRelSlaveRep.Context.Queryable<DeviceSlaveTemplate>()
                .Select(u => new
                {
                    Label = u.SlaveName,
                    Value = u.Id
                }
                ).ToListAsync();
    }

    /// <summary>
    /// 获取设备id列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeviceInfoDeviceInfoIdDropdown"), HttpGet]
    [DisplayName("获取设备id列表")]
    public async Task<dynamic> DeviceInfoDeviceInfoIdDropdown()
    {
        return await _deviceRelSlaveRep.Context.Queryable<DeviceInfo>()
                .Select(u => new
                {
                    Label = u.DeviceName,
                    Value = u.Id
                }
                ).ToListAsync();
    }
}